package com.example.haoqisystem.Exception;


import com.example.haoqisystem.response.BaseResponse;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 不加 @RequestBody注解，校验失败抛出的则是 BindException
     */
    @ExceptionHandler(BindException.class)
    public BaseResponse<Object> bindExceptionHandler(BindException e) {
        String msg = e.getAllErrors().get(0).getDefaultMessage();
        return new BaseResponse<>("参数校验失败",false,msg);
    }
    /**
     * @RequestBody 上校验失败后抛出的异常是 MethodArgumentNotValidException 异常。
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String msg = bindingResult.getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining("；"));
        return new BaseResponse<>("参数校验失败",false,msg);
    }

    /**
     *  @RequestParam 上校验失败后抛出的异常是 ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponse<Object> methodArgumentNotValid(ConstraintViolationException e) {
        String msg =  e.getMessage();
        return new BaseResponse<>("参数校验失败",false,msg);
    }
    /**
     *  非法参数
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public BaseResponse<Object> illegalArgumentHandler(IllegalArgumentException e) {
        return new BaseResponse<>("非法参数",false,e.getMessage());
    }

}
